<?php 

namespace Topxia\AdminBundle\Controller;

use Topxia\AdminBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
use Topxia\Common\Paginator;
use Topxia\Service\Common\ServiceException;


class LearningCardController extends BaseController

{

	//学习卡的首页
	public function indexAction(Request $request)
	{	

		//获取学习卡适用范围
		$res = $this->getCategoryService()->findAllCategories();
		// var_dump($res);

		//获取学习卡的批次
		$batch = $this->getLearningCardService()->getMaxBatch();
		$maxbatch = $batch[0]['MAX(batch)'];
		//获取学习卡的批次
		$info = $this->getLearningCardService()->getBatch();

		$res1 = $this->getLearningCardService()->getInfo();


// var_dump($res1);die;


		//查询已经生成的学习卡的总量
		$num = $this->getLearningCardService()->getNum();
		//查询一共已有多少学习卡已经充值
		$czNum = $this->getLearningCardService()->getCzNum();
		return $this->render('TopxiaAdminBundle:Learningcard:index.html.twig',array(
			'info'=>$info,
			'maxbatch' => ($maxbatch),
			'res'  => $res,
			'anum' =>$num[0]["count(id)"],
			'czNum' => $czNum[0]["count(id)"],
			'res1' => $res1
	
			));

	}
	//学习卡管理的详情页面
	public function detailAction(Request $request)
	{  
		$sbatch = $request->get('batch');
		// var_dump($batch);die;
		//获取学习卡适用范围
		$res = $this->getCategoryService()->findAllCategories();
		// var_dump($res);

		//获取学习卡的批次
		$sbatch = $request ? $request->query->all() : array();
        $sbatch['cardId'] = isset($sbatch['cardId']) ? trim($sbatch['cardId']) : null;
        $sbatch['batch'] = isset($sbatch['batch']) ? trim($sbatch['batch']) : null;

		$batch = $this->getLearningCardService()->getMaxBatch();
		$maxbatch = $batch[0]['MAX(batch)'];
		//获取学习卡的总数
		
		$total = $this->getLearningCardService()->total1($sbatch);
		
		//分页
		$paginator = new Paginator($request,$total[0]["count(id)"], 20);
		
		//获取学习卡的信息
		$card = $this->getLearningCardService()->get($paginator->getOffsetCount(), $paginator->getPerPageCount(),$sbatch);
		//判断学习卡是否过期 改变学习卡的
		foreach ($card as $k => $v) {
			$time = time();
			if($v['usetime'] < $time && $v['usetime'] != 0){
				$status = 2;
				$id = $v['id'];
				$userId = 0;
				$rechargetime= '0';
				$this->getLearningCardService()->updateStatus($status,$id,$userId,$rechargetime);
			}
		}
		$card = $this->getLearningCardService()->get($paginator->getOffsetCount(), $paginator->getPerPageCount(),$sbatch);

		return $this->render('TopxiaAdminBundle:Learningcard:detail.html.twig',array(
			// 'tag'  =>$tag,
			'res'  => $res,
			'card' =>$card,
			'paginator' =>$paginator,
			'maxbatch' => ($maxbatch)
			// 'category' =>$category
	
		));

	}

	//学习卡号的生成
	public function buildAction(Request $request)
	{

		
		$conditions = array();
		//获得生成的数量
		$num = $request->get('num');
		//获得面额
		$money = $request->get('money');
		//获得学习卡的充值有效期
		$time = $request->get('usetime');
		if(empty($time)){
			$time = 0;
		}
		// var_dump($time);die;
		//获得学习卡的类别
		$category = $request->get('category');

		//获得学习卡的批次
		$batch = $request->get('batch');
		//获得学习卡的适用范围
		$cateId = $request->get('cateId');
		//获得学习卡充值以后得有效期
		$valid = $request->get('valid');
		//获得学习卡的类型
		$type = $request->get('type');
		//获得学习卡的标题
		$title = $request->get('title');
			
			//当前输入的批次数大于已有批次的最大数
				$conditions['category'] = $category;
				$conditions['num'] = $num;
				$conditions['money'] = $money;
				if($time == '0'){
					$conditions['usetime'] = $time*3600*24*30;

				}else{
					$conditions['usetime'] = $time*3600*24*30+time();

				}
				$conditions['ctime'] = time();
				$conditions['batch'] = $batch;
				$conditions['cateId'] = $cateId;
				$conditions['type'] = $type;
				$conditions['valid'] =$valid;
				$conditions['title'] = $title;

				// var_dump($conditions);die;
				$success = $this->getLearningCardService()->buildding($conditions);
				// var_dump($success);die;
				if($success == '1'){
					$this->setFlashMessage('success', '生成成功！');
				}else{
					$this->setFlashMessage('error', '生成失败');
				}
		return $this->redirect($this->generateUrl('admin_learningcard'));
	

	
	}

	//学习卡的删除
	public function deleteAction( Request $request )
	{
		$id = $request->get('id');
		$res = $this->getLearningCardService()->delete($id);
		if($res == '1'){
			$this->setFlashMessage('success', '删除成功！');
		}else{
			$this->setFlashMessage('error', '删除失败！');
		}
		return $this->redirect($this->generateUrl('admin_learningcard'));

	}

	//学习卡批次的查询
	public function searchAction(Request $request)
	{	
		//获取需要查询已充值的学习卡的批次
		$nbatch = $request->get('nbatch');
		
		
		
		
		$nbatch = ltrim($nbatch,',');
		$nbatch = explode(',',$nbatch);
		$nbatch = implode(',',$nbatch);
		//查询已经充值的学习卡的数量
		$cNum= $this->getLearningCardService()->getCnum($nbatch);
		$noNum = $this->getLearningCardService()->getNoNum($nbatch);
		//查询已经生成的学习卡的总量
		$num = $this->getLearningCardService()->getNum();		
		//查询一共已有多少学习卡已经充值
		$czNum = $this->getLearningCardService()->getCzNum();
		

		//获取学习卡适用范围
		$res = $this->getCategoryService()->findAllCategories();
		$conditions = array();

		
		//获取批次号
		$batch = $request->get('batch');
		$conditions['batch']  =$batch;
		
		//获取学习卡的批次
		
		$batch = $this->getLearningCardService()->getMaxBatch();
		$maxbatch = $batch[0]['MAX(batch)'];
		//获取条件查询总数
		$total = $this->getLearningCardService()->total1($conditions);
		
		
		//条件查询分页
		$paginator = new Paginator($this->get('request'),$total[0]["count(id)"], 20);
		
		$info = $this->getLearningCardService()->search($conditions,$paginator->getOffsetCount(), $paginator->getPerPageCount());
		
		
		
		$res1 = $this->getLearningCardService()->getInfo();
		
		
		
		return $this->render('TopxiaAdminBundle:Learningcard:index.html.twig',array(
			'res'  =>$res,
			'info' =>$info,
			'paginator' =>$paginator,
			'maxbatch' =>$maxbatch,
			'cNum' =>$cNum[0]["count(id)"],
			'czNum' =>$czNum[0]["count(id)"],
			'noNum' =>$noNum[0]["count(id)"],

			'anum' =>$num[0]["count(id)"],
			'nbatch' => $nbatch,
			'res1' =>$res1

	
			));
	}

	//学习卡详情页面的学习卡号的查询
	public function searchIdAction(Request $request)
	{	
		//获取学习卡的适用范围
		$res = $this->getCategoryService()->findAllCategories();
		$conditions = array();



		//获取学习卡的卡号
		$conditions = $request ? $request->query->all() : array();
        $conditions['cardId'] = isset($conditions['cardId']) ? trim($conditions['cardId']) : null;
        $conditions['batch'] = isset($conditions['batch']) ? trim($conditions['batch']) : null;
		//获取学习卡的批次
		
		$batch = $this->getLearningCardService()->getMaxBatch();
		$maxbatch = $batch[0]['MAX(batch)'];
		//获取条件查询总数
		$total = $this->getLearningCardService()->total1($conditions);
		
		//条件查询分页
		$paginator = new Paginator($request,$total[0]["count(id)"], 20);
		$card = $this->getLearningCardService()->searchId($conditions,$paginator->getOffsetCount(), $paginator->getPerPageCount());
		return $this->render('TopxiaAdminBundle:Learningcard:detail.html.twig',array(
			'res'  =>$res,
			'card' =>$card,
			'paginator' =>$paginator,
			'maxbatch' =>$maxbatch
			));

	}

	//按批次导出学习卡
	public function excelAction(Request $request)
	{	
		$batch= $request->get('batch');
		// var_dump($batch);die;
		$savename = '第'.$batch.'批';
		$file_type = "vnd.ms-excel"; 
		$file_ending = "csv";
		header("Content-Type: application/$file_type;charset=big5");
		header("Content-Disposition: attachment; filename=".$savename.".$file_ending"); 
     	$res1 = $this->getLearningCardService()->selectFields();
     	
     	
   		foreach($res1 as $k=>$v){
    		// echo $v['Field'].",";
    		if($v['Field']=='id'){
    			echo iconv("utf-8","gb2312",'学习卡生成id号').',';
    		}
    		if($v['Field']=='cardId'){
    			echo iconv("utf-8","gb2312",'学习卡号').',';
    		}
    		if($v['Field']=='usetime'){
    			echo iconv("utf-8","gb2312",'充值到期时间').',';
    		}
    		if($v['Field']=='status'){
    			echo iconv("utf-8","gb2312",'学习卡状态').',';

    		}
    		if($v['Field']=='money'){
    			echo iconv("utf-8","gb2312",'学习卡面额').',';

    		}
    		if($v['Field']=='ctime'){
    			echo iconv("utf-8","gb2312",'学习卡生成时间').',';

    		}
    		if($v['Field']=='category'){
    			echo iconv("utf-8","gb2312",'学习卡分类ID').',';

    		}
    		if($v['Field']=='userId'){
    			echo iconv("utf-8","gb2312",'充值者ID').',';

    		}
    		if($v['Field']=='batch'){
    			echo iconv("utf-8","gb2312",'学习卡的批次').',';

    		}
    		if($v['Field']=='cateId'){
    			echo iconv("utf-8","gb2312",'学习卡适用范围ID').',';

    		}
    		
    		if($v['Field']=='valid'){
    			echo iconv("utf-8","gb2312",'充值以后到期时间').',';

    		}
    		if($v['Field']=='type'){
    			echo iconv("utf-8","gb2312",'学习卡类型').',';

    		}
    		if($v['Field']=='rechargetime'){
    			echo iconv("utf-8","gb2312",'学习卡充值日期').',';

    		}
    		if($v['Field']=='title'){
    			echo iconv("utf-8","gb2312",'学习卡标题');

    		}
    	}
    	echo "\n";
		$t=0;
		while($res = $this->getLearningCardService()->selectBatch($batch,$t)){
			$t++;
			for($i=0;$i<count($res);$i++){

				echo $res[$i]['id'].",";
				echo $res[$i]['cardId'].",";
				echo $res[$i]['usetime'].",";
				echo $res[$i]['status'].",";
				echo $res[$i]['money'].",";
				echo $res[$i]['ctime'].",";
				echo $res[$i]['category'].",";
				echo $res[$i]['userId'].",";
				echo $res[$i]['batch'].",";
				echo $res[$i]['cateId'].",";
				echo $res[$i]['valid'].",";
				echo $res[$i]['type'].",";
				echo $res[$i]['rechargetime'].",";
				echo iconv("utf-8","gb2312",$res[$i]['title'])."\n";
			}
		}
     
    
   
      	exit;
      	

	}



	protected function getLearningCardService()
	{
		return $this->getServiceKernel()->createService('Kuke.LearningCardService');
	}

  protected function getCategoryService()
    {
        return $this->getServiceKernel()->createService('Taxonomy.CategoryService');
    }


}


 ?>
